package com.csun.cmny.provider.device.card;

import com.csun.cmny.provider.device.card.entity.CardCmdEntity;
import com.csun.cmny.provider.device.relay.RelayMessageHandler;
import com.csun.cmny.provider.device.relay.entity.RelayCmdWidEntity;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-11-28 20:42
 * @Description:
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class CardNettyTcpServerHandler extends ChannelInboundHandlerAdapter {

    @Resource
    private CardMessageHandler cardMessageHandler;

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {

        log.info("# card client registered...：   {} ...", ctx.channel());

        // 查询设备编号命令
        // String cmd = RelayCmdWidEntity.buildCmdQuery();

        // 发送数据
        // ctx.channel().writeAndFlush(Unpooled.copiedBuffer(cmd, CharsetUtil.UTF_8));
    };

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        try {
            ByteBuf in = (ByteBuf) msg;
            if (in != null) {
                // 处理接收的数据

                byte[] receiveMsg = new byte[in.readableBytes()];
                in.readBytes(receiveMsg);

                log.info("# card read...: [{}]", CardMessageEncoder.format(Hex.encodeHexString(receiveMsg)));

                CardCmdEntity cardCmdEntity = CardMessageDecoder.parse(receiveMsg);
                if (cardCmdEntity == null) {
                    log.error("=====>  card read message not parse");
                    return ;
                }

                cardMessageHandler.handler(ctx, cardCmdEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("=====>  card channel read error: {}", e.getMessage());
        } finally {
            // 抛弃收到的数据
            ReferenceCountUtil.release(msg);
        }
    }

    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        log.info("card channel inactive ... {}", ctx.toString());

        ctx.close();
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        log.info("card channel exception caught... {}, cause = {}", ctx.toString(), cause.getMessage());

        ctx.close();
    }

}
